// uni-id-scores/index.js
var db = uniCloud.database()
const dbCmd = db.command
const $ = dbCmd.aggregate

exports.main = async (event, context) => {
	const {
		user_id,
		score,
		comment,
		type
	} = event
	const transaction = await db.startTransaction()
	// 参数校验
	if (!user_id || !score || score <= 0) {
		return {
			code: 400,
			msg: '参数错误'
		}
	}

	try {
		// 获取当前用户积分
		const userRes = await transaction.collection('uni-id-users').doc(user_id).get()
		console.log(userRes.data.score)
		const currentScore = userRes.data.score || 0
		let newBalance = 0
		if (type == 1) {
			newBalance = currentScore + score
		} else {
			newBalance = currentScore - score
		}




		// 插入积分记录
		transaction.collection('uni-id-scores').add({
			user_id,
			score,
			type, // 1表示收入,2表示支出
			balance: newBalance,
			comment,
			create_date: Date.now()
		})
		

		// 更新用户积分
		transaction.collection('uni-id-users').doc(user_id).update({
			score: newBalance
		})
		await transaction.commit()
		return {
			code: 200,
			msg: '充值成功',
			data: newBalance
		}
	} catch (e) {
		await transaction.rollback()
		return {
			code: 500,
			msg: '充值失败：' + e.message
		}
	}
}